<template>
  <div class="sales-order-list-page">
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">销售订单管理</h2>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="createOrder">
          <i class="fa fa-plus"></i> 新建订单
        </el-button>
      </div>
    </div>
    
    <div class="search-section">
      <el-card shadow="never">
        <template #header>
          <div class="search-header">
            <span>搜索条件</span>
            <el-button type="text" @click="toggleAdvanced">
              {{ isAdvanced ? '收起' : '展开' }}高级搜索
              <i :class="isAdvanced ? 'fa fa-chevron-up' : 'fa fa-chevron-down'"></i>
            </el-button>
          </div>
        </template>
        
        <el-form :model="searchForm" label-width="80px" @submit.prevent="handleSearch">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="订单编号">
                <el-input v-model="searchForm.orderId" placeholder="请输入订单编号" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户名称">
                <el-input v-model="searchForm.customerName" placeholder="请输入客户名称" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="销售人员">
                <el-select v-model="searchForm.salesperson" placeholder="选择销售人员" clearable style="width: 100%">
                  <el-option v-for="item in salesPersonOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <div v-show="isAdvanced">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="日期范围">
                  <el-date-picker
                    v-model="searchForm.dateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="订单状态">
                  <el-select v-model="searchForm.status" placeholder="选择订单状态" clearable style="width: 100%">
                    <el-option label="全部" value=""></el-option>
                    <el-option label="已完成" value="completed"></el-option>
                    <el-option label="处理中" value="pending"></el-option>
                    <el-option label="已取消" value="cancelled"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="金额范围">
                  <div class="amount-range">
                    <el-input-number v-model="searchForm.minAmount" placeholder="最小金额" :min="0" :precision="2" :step="1000" :controls="false"></el-input-number>
                    <span class="range-separator">至</span>
                    <el-input-number v-model="searchForm.maxAmount" placeholder="最大金额" :min="0" :precision="2" :step="1000" :controls="false"></el-input-number>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          
          <div class="search-buttons">
            <el-button type="primary" @click="handleSearch">
              <i class="fa fa-search"></i> 搜索
            </el-button>
            <el-button @click="resetSearch">
              <i class="fa fa-refresh"></i> 重置
            </el-button>
          </div>
        </el-form>
      </el-card>
    </div>
    
    <div class="table-section">
      <el-card shadow="never" class="table-card">
        <div class="table-header">
          <div class="table-title">订单列表</div>
          <div class="table-actions">
            <el-button size="small" @click="exportData">
              <i class="fa fa-download"></i> 导出
            </el-button>
            <el-button size="small" @click="printData">
              <i class="fa fa-print"></i> 打印
            </el-button>
            <el-button size="small" @click="refreshData">
              <i class="fa fa-refresh"></i> 刷新
            </el-button>
          </div>
        </div>
        
        <el-table
          v-loading="tableLoading"
          :data="tableData"
          style="width: 100%"
          border
          stripe
          highlight-current-row
          @row-click="handleRowClick"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="id" label="订单编号" width="160" sortable>
            <template #default="scope">
              <el-button type="text" @click.stop="viewOrderDetail(scope.row)">{{ scope.row.id }}</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="date" label="创建日期" width="120" sortable />
          <el-table-column prop="customerName" label="客户名称" min-width="180" show-overflow-tooltip />
          <el-table-column prop="salesperson" label="销售人员" width="120" />
          <el-table-column prop="amount" label="订单金额" width="150" sortable align="right">
            <template #default="scope">
              {{ formatCurrency(scope.row.amount) }}
            </template>
          </el-table-column>
          <el-table-column prop="paymentStatus" label="付款状态" width="120">
            <template #default="scope">
              <el-tag :type="getPaymentStatusType(scope.row.paymentStatus)" size="small">
                {{ getPaymentStatusText(scope.row.paymentStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="订单状态" width="120">
            <template #default="scope">
              <el-tag :type="getOrderStatusType(scope.row.status)" size="small">
                {{ getOrderStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button size="small" @click.stop="viewOrderDetail(scope.row)">查看</el-button>
              <el-button size="small" type="primary" @click.stop="editOrder(scope.row)" :disabled="scope.row.status === 'completed'">编辑</el-button>
              <el-dropdown size="small" @command="(command) => handleCommand(command, scope.row)">
                <el-button size="small">
                  更多<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="print">打印订单</el-dropdown-item>
                    <el-dropdown-item command="copy">复制订单</el-dropdown-item>
                    <el-dropdown-item command="cancel" :disabled="scope.row.status === 'completed' || scope.row.status === 'cancelled'">取消订单</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

// 模拟获取订单列表API
const fetchOrderList = async (params: any) => {
  console.log('获取订单列表，参数:', params)
  
  // 这里应该是实际的API调用
  // 模拟数据
  const { page, pageSize } = params
  
  // 模拟订单数据
  const orders = []
  const total = 235
  
  for (let i = 0; i < pageSize; i++) {
    const index = (page - 1) * pageSize + i
    if (index >= total) break
    
    orders.push({
      id: `SO${230000 + index}`,
      date: `2023-${Math.floor(Math.random() * 12) + 1}-${Math.floor(Math.random() * 28) + 1}`,
      customerName: `客户${index % 10 + 1}`,
      salesperson: `销售员${index % 5 + 1}`,
      amount: Math.floor(Math.random() * 100000) / 100,
      paymentStatus: ['unpaid', 'partially_paid', 'paid'][Math.floor(Math.random() * 3)],
      status: ['pending', 'processing', 'completed', 'cancelled'][Math.floor(Math.random() * 4)],
    })
  }
  
  return {
    total,
    data: orders
  }
}

export default defineComponent({
  name: 'SalesOrderList',
  setup() {
    const router = useRouter()
    
    // 高级搜索开关
    const isAdvanced = ref(false)
    
    // 表格加载状态
    const tableLoading = ref(false)
    
    // 销售人员选项
    const salesPersonOptions = [
      { value: '1', label: '销售员1' },
      { value: '2', label: '销售员2' },
      { value: '3', label: '销售员3' },
      { value: '4', label: '销售员4' },
      { value: '5', label: '销售员5' }
    ]
    
    // 搜索表单
    const searchForm = reactive({
      orderId: '',
      customerName: '',
      salesperson: '',
      dateRange: null as [string, string] | null,
      status: '',
      minAmount: null as number | null,
      maxAmount: null as number | null
    })
    
    // 表格数据
    const tableData = ref([])
    
    // 分页相关
    const currentPage = ref(1)
    const pageSize = ref(20)
    const total = ref(0)
    
    // 切换高级搜索
    const toggleAdvanced = () => {
      isAdvanced.value = !isAdvanced.value
    }
    
    // 搜索处理
    const handleSearch = async () => {
      currentPage.value = 1
      fetchData()
    }
    
    // 重置搜索条件
    const resetSearch = () => {
      Object.keys(searchForm).forEach(key => {
        // @ts-ignore
        searchForm[key] = key === 'status' ? '' : null
      })
      searchForm.orderId = ''
      searchForm.customerName = ''
      searchForm.salesperson = ''
      
      currentPage.value = 1
      fetchData()
    }
    
    // 获取表格数据
    const fetchData = async () => {
      tableLoading.value = true
      
      try {
        // 构建查询参数
        const params = {
          page: currentPage.value,
          pageSize: pageSize.value,
          orderId: searchForm.orderId,
          customerName: searchForm.customerName,
          salesperson: searchForm.salesperson,
          startDate: searchForm.dateRange?.[0] || null,
          endDate: searchForm.dateRange?.[1] || null,
          status: searchForm.status,
          minAmount: searchForm.minAmount,
          maxAmount: searchForm.maxAmount
        }
        
        const result = await fetchOrderList(params)
        tableData.value = result.data
        total.value = result.total
      } catch (error) {
        console.error('获取订单列表失败:', error)
        ElMessage.error('获取订单列表失败，请稍后重试')
      } finally {
        tableLoading.value = false
      }
    }
    
    // 处理页码变化
    const handleCurrentChange = (page: number) => {
      currentPage.value = page
      fetchData()
    }
    
    // 处理每页条数变化
    const handleSizeChange = (size: number) => {
      pageSize.value = size
      currentPage.value = 1
      fetchData()
    }
    
    // 导出数据
    const exportData = () => {
      ElMessage.success('导出功能待实现')
    }
    
    // 打印数据
    const printData = () => {
      ElMessage.success('打印功能待实现')
    }
    
    // 刷新数据
    const refreshData = () => {
      fetchData()
      ElMessage.success('数据已刷新')
    }
    
    // 新建订单
    const createOrder = () => {
      router.push('/yxerp/sales/order/create')
    }
    
    // 查看订单详情
    const viewOrderDetail = (row: any) => {
      router.push(`detail/${row.id}`)
    }
    
    // 编辑订单
    const editOrder = (row: any) => {
      router.push(`/#/admin/yxerp/sales/order/edit/${row.id}`)
    }
    
    // 处理更多操作命令
    const handleCommand = (command: string, row: any) => {
      if (command === 'print') {
        ElMessage.success(`打印订单: ${row.id}`)
      } else if (command === 'copy') {
        ElMessage.success(`复制订单: ${row.id}`)
      } else if (command === 'cancel') {
        ElMessageBox.confirm(`确定要取消订单 ${row.id} 吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          ElMessage.success(`订单 ${row.id} 已取消`)
          // 更新数据
          fetchData()
        }).catch(() => {
          // 取消操作
        })
      }
    }
    
    // 处理行点击
    const handleRowClick = (row: any) => {
      viewOrderDetail(row)
    }
    
    // 格式化货币
    const formatCurrency = (value: number) => {
      return new Intl.NumberFormat('zh-CN', {
        style: 'currency',
        currency: 'CNY',
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      }).format(value)
    }
    
    // 获取付款状态类型
    const getPaymentStatusType = (status: string) => {
      switch (status) {
        case 'paid': return 'success'
        case 'partially_paid': return 'warning'
        case 'unpaid': return 'danger'
        default: return 'info'
      }
    }
    
    // 获取付款状态文本
    const getPaymentStatusText = (status: string) => {
      switch (status) {
        case 'paid': return '已付款'
        case 'partially_paid': return '部分付款'
        case 'unpaid': return '未付款'
        default: return '未知'
      }
    }
    
    // 获取订单状态类型
    const getOrderStatusType = (status: string) => {
      switch (status) {
        case 'completed': return 'success'
        case 'processing': return 'primary'
        case 'pending': return 'warning'
        case 'cancelled': return 'info'
        default: return 'info'
      }
    }
    
    // 获取订单状态文本
    const getOrderStatusText = (status: string) => {
      switch (status) {
        case 'completed': return '已完成'
        case 'processing': return '处理中'
        case 'pending': return '待处理'
        case 'cancelled': return '已取消'
        default: return '未知'
      }
    }
    
    // 组件挂载时加载数据
    onMounted(() => {
      fetchData()
    })
    
    return {
      isAdvanced,
      tableLoading,
      salesPersonOptions,
      searchForm,
      tableData,
      currentPage,
      pageSize,
      total,
      toggleAdvanced,
      handleSearch,
      resetSearch,
      handleCurrentChange,
      handleSizeChange,
      exportData,
      printData,
      refreshData,
      createOrder,
      viewOrderDetail,
      editOrder,
      handleCommand,
      handleRowClick,
      formatCurrency,
      getPaymentStatusType,
      getPaymentStatusText,
      getOrderStatusType,
      getOrderStatusText
    }
  }
})
</script>

<style scoped lang="scss">
.sales-order-list-page {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .page-title {
      margin: 0;
      font-size: 22px;
      font-weight: 600;
      color: #303133;
    }
  }
  
  .search-section {
    margin-bottom: 20px;
    
    .search-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 16px;
      font-weight: 500;
    }
    
    .amount-range {
      display: flex;
      align-items: center;
      
      .range-separator {
        margin: 0 10px;
        color: #909399;
      }
    }
    
    .search-buttons {
      margin-top: 20px;
      display: flex;
      justify-content: center;
      gap: 15px;
    }
  }
  
  .table-section {
    .table-card {
      margin-bottom: 20px;
    }
    
    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      
      .table-title {
        font-size: 16px;
        font-weight: 500;
      }
      
      .table-actions {
        display: flex;
        gap: 10px;
      }
    }
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style> 